package com.hll.utils;

import java.util.Calendar;
import java.util.Date;

/**
 * 工具类
 *
 * @program: smbms
 * @description: sas
 * @author: Mr.Hu
 * @create: 2021-03-07 12:01
 */
public class Calculator {
  /**
   * 通过Date对象获取年龄
   *
   * @param: [birthDay]
   * @return: int gae
   * @author: Mr.Hu
   * @date: 2021-3-7
   */
  public static int getAge(Date birthDay) {
    Calendar cal = Calendar.getInstance();
    if (cal.before(birthDay)) { // 出生日期晚于当前时间，无法计算
      throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
    }
    int yearNow = cal.get(Calendar.YEAR); // 当前年份
    int monthNow = cal.get(Calendar.MONTH); // 当前月份
    int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); // 当前日期
    cal.setTime(birthDay); // 设置生日date,然后获取year..
    int yearBirth = cal.get(Calendar.YEAR);
    int monthBirth = cal.get(Calendar.MONTH);
    int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
    int age = yearNow - yearBirth; // 计算整岁数
    if (monthNow <= monthBirth) {
      if (monthNow == monthBirth) {
        if (dayOfMonthNow < dayOfMonthBirth) age--; // 当前日期在生日之前，年龄减一
      } else {
        age--; // 当前月份在生日之前，年龄减一
      }
    }
    return age;
  }
}
